<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="theme-color" content="#6b4f4f">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="纪念D仔">
    <link rel="apple-touch-icon" href="favicon.ico">
    <title>帝姬/D仔的空间</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f9f5f0;
            color: #444;
            line-height: 1.8;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 40px 20px;
            text-align: center;
        }
        h1 { font-size: 2.5em; color: #6b4f4f; margin-bottom: 10px; }
        .subtitle { font-size: 1.2em; color: #888; margin-bottom: 30px; }
        .section { background: white; padding: 30px; margin: 30px 0; border-radius: 15px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); text-align: left; }
        .photo-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        .photo-item {
            position: relative;
        }
        .photo-grid img {
            width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 10px 10px 0 0;
            border: 1px solid #eee;
            border-bottom: none;
        }
        .photo-caption {
            background: #f8f8f8;
            color: #555;
            padding: 8px 10px;
            border-radius: 0 0 10px 10px;
            font-size: 0.85em;
            border: 1px solid #eee;
            border-top: none;
            min-height: 40px;
            display: flex;
            align-items: center;
        }
        .photo-caption.empty {
            color: #aaa;
            font-style: italic;
        }
        .candle {
            margin: 20px 0;
            font-size: 1.2em;
            color: #a06a6a;
        }
        .candle button {
            background: #e89a9a; color: white; border: none; padding: 10px 20px;
            border-radius: 20px; cursor: pointer; margin-top: 10px; font-size: 1em;
        }
        textarea, input { width: 100%; padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius: 8px; }
        .message-list { margin-top: 20px; }
        .message { padding: 10px; background: #f0e6e6; margin: 10px 0; border-radius: 8px; font-size: 0.95em; }
        footer { margin-top: 50px; color: #aaa; font-size: 0.9em; }

        /* 加载更多按钮样式 */
        .load-more {
            background: #6b4f4f;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            margin: 20px 0;
            display: block;
            width: 100%;
        }

        .load-more:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .load-more.loading {
            background: #999;
        }
        /* 音乐控制按钮样式 */
        .music-control {
            position: fixed;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 999;
            background: #6b4f4f;
            color: white;
            border: none;
            border-radius: 0 30px 30px 0;
            padding: 15px 12px 15px 18px;
            cursor: pointer;
            box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            font-size: 14px;
            font-family: 'Segoe UI', sans-serif;
        }

        .music-control:hover {
            background: #8a6d6d;
        }

        .music-control.minimized {
            padding: 12px 8px;
            border-radius: 50%;
            left: 10px;
        }

        .music-control.minimized .music-text {
            display: none;
        }

        .music-control.minimized .music-icon {
            margin: 0;
        }

        .music-icon {
            font-size: 18px;
            margin-right: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .music-bars {
            display: flex;
            align-items: center;
            height: 20px;
            margin-right: 8px;
        }

        .music-bar {
            width: 3px;
            height: 100%;
            background: white;
            margin: 0 1px;
            animation: sound 0ms -800ms linear infinite alternate;
        }

        .music-bar:nth-child(1) { animation-duration: 474ms; }
        .music-bar:nth-child(2) { animation-duration: 433ms; }
        .music-bar:nth-child(3) { animation-duration: 407ms; }
        .music-bar:nth-child(4) { animation-duration: 458ms; }

        @keyframes sound {
            0% { opacity: .35; height: 30%; }
            100% { opacity: 1; height: 100%; }
        }


        /* 移动端优化 */
        @media (max-width: 768px) {
            .container {
                padding: 20px 15px;
            }

            .section {
                padding: 20px;
                margin: 20px 0;
            }

            h1 {
                font-size: 2em;
            }

            .photo-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 10px;
            }

            .photo-grid img {
                height: 150px;
            }

            textarea, input {
                font-size: 16px; /* 防止iOS缩放 */
            }
            .music-control {
                left: 10px;
                padding: 12px 10px 12px 15px;
                font-size: 12px;
            }

            .music-control.minimized {
                padding: 10px;
                left: 5px;
            }

            .music-icon {
                font-size: 16px;
            }
        }

        /* 文件上传按钮在移动端的优化 */
        input[type="file"] {
            font-size: 14px;
        }

        @media (max-width: 768px) {
            input[type="file"] {
                font-size: 16px; /* 防止iOS Safari缩放 */
            }
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            animation: fadeIn 0.3s ease;
        }

        .modal-content {
            display: block;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
        }

        .modal-caption {
            position: absolute;
            bottom: 20px;
            left: 0;
            right: 0;
            text-align: center;
            color: white;
            font-size: 1.2em;
            padding: 10px;
            background: rgba(0, 0, 0, 0.5);
        }

        .close {
            position: absolute;
            top: 20px;
            right: 30px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
            z-index: 1001;
        }

        .close:hover,
        .close:focus {
            color: #bbb;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            .modal-content {
                max-width: 95%;
                max-height: 85%;
            }

            .close {
                font-size: 30px;
                top: 10px;
                right: 15px;
            }

            .modal-caption {
                font-size: 1em;
                bottom: 10px;
            }
        }
    </style>
</head>
<body>
<!-- 添加背景音乐控制按钮 -->
<button id="musicControl" class="music-control minimized">
    <div class="music-bars">
        <div class="music-bar"></div>
        <div class="music-bar"></div>
        <div class="music-bar"></div>
        <div class="music-bar"></div>
    </div>
    <span class="music-text">背景音乐</span>
</button>

<!-- 添加音频元素 -->
<audio id="backgroundMusic" loop muted>
    <source src="{{ asset('music/music.mp3') }}" type="audio/mpeg">
    您的浏览器不支持音频元素。
</audio>
<div class="container">
    <h1>纪念 帝姬（小D / D仔）</h1>
    <p class="subtitle">2021年12月18日~2025年8月5日</p>
    <p>你轻轻走过我们的岁月，像一缕阳光洒在窗台<br>你不曾说话，却懂所有的温柔<br>谢谢你曾来过，我们永远记得你呼噜呼噜的声音</p>

    <div class="section">
        <h2>关于D仔</h2>
        <p>帝姬（小D / D仔），一只蠢萌又胆小的猫咪，从2021年12月18日正式走进我们的生活，用近四年的陪伴，点亮了无数个平凡的日子；它既谨慎警惕又不怕生，谁来都能上手撸；
            别人家的猫总能捉点什么，它却只会罚站，只等蟑螂爬到它jiojio；
            白天一副高冷的样子，却总在深夜悄悄爬上床；它看起来傻乎乎的，却最懂得什么时候该蹭蹭你，什么时候安静陪伴。</p>
        <p>它不是最聪明的猫，却是最懂爱的一只</p>
    </div>

    <div class="section">
        <h2>萌照</h2>
        <div class="photo-grid" id="photoGrid">
            <!-- 图片将通过JS动态添加 -->
        </div>

        <button id="loadMorePhotos" class="load-more" style="display: none;">
            加载更多萌照
        </button>

        <!-- 添加萌照上传表单 -->
        <div style="margin-top: 20px; padding: 15px; border: 1px dashed #ccc; border-radius: 8px;">
            <h3>上传萌照</h3>
            <form id="photoUploadForm" enctype="multipart/form-data">
                <div style="margin: 15px 0;">
                    <label for="photoInput" style="display: block; margin-bottom: 8px; font-weight: bold;">选择萌照：</label>
                    <input type="file" id="photoInput" name="photos[]" accept="image/*" multiple required                   style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                    <p style="font-size: 0.8em; color: #666; margin-top: 5px;">支持PNG、JPG、JPEG格式，每张最大10MB，可多选</p>
                    <p style="font-size: 0.8em; color: #888; margin-top: 5px;">注意：请勿上传重复萌照（最多同时上传10张）</p>
                </div>

                <!-- 图片预览区域 -->
                <div id="previewContainer" style="margin: 15px 0; display: none;">
                    <h4>图片预览</h4>
                    <div id="previewGrid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; margin-top: 10px;">
                        <!-- 预览图片将在这里添加 -->
                    </div>
                </div>

                <div id="captionContainer" style="margin: 15px 0;">
                    <!-- 动态生成的描述输入框将在这里添加 -->
                </div>

                <button type="submit" id="uploadButton"                style="background: #6b4f4f; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; width: 100%; font-size: 16px;">
                    上传萌照
                </button>
            </form>
        </div>

        <p style="font-size:0.9em; color:#888;">你可以上传更多萌照来丰富这个角落</p>
    </div>

    <div class="section">
        <h2>点亮一盏灯 ️</h2>
        <p>如果你也想念D仔，欢迎点亮一盏灯，让它知道，它从未被忘记</p>
        <div class="candle">
            <span id="candleCount">已有 {{ $candleCount }} 人</span> 为D仔点亮了灯
            <button onclick="lightCandle()">点亮一盏灯</button>
        </div>
    </div>

    <div class="section">
        <h2>留下你的回忆 </h2>
        <p>欢迎写下你对D仔的思念、故事或祝福</p>
        <textarea id="messageInput" rows="4" placeholder="例如：我记得它最爱趴在阳台上晒太阳……"></textarea>
        <input id="nameInput" placeholder="你的名字（可选）"/>
        <button onclick="submitMessage()" style="background:#6b4f4f;color:white;padding:10px 20px;border:none;border-radius:8px;cursor:pointer;">提交留言</button>

        <div class="message-list" id="messageList">
            <!-- 留言将显示在这里 -->
        </div>

        <button id="loadMoreMessages" class="load-more" style="display: none;">
            加载更多留言
        </button>
    </div>
</div>

<footer class="container">
    {{--    <p>愿D仔在彩虹桥上自由奔跑，不再胆小，永远有阳光和呼噜声</p>--}}
    <p style="margin-top:10px; font-size:0.8em;">愿D仔在彩虹桥上自由奔跑，不再胆小，永远有阳光和呼噜声</p>
</footer>


<script>
    // 设置CSRF token
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    // 当前页码状态
    let photoPage = 1;
    let messagePage = 1;
    let hasMorePhotos = true;
    let hasMoreMessages = true;

    document.addEventListener('DOMContentLoaded', function() {
        const musicControl = document.getElementById('musicControl');
        const backgroundMusic = document.getElementById('backgroundMusic');
        const musicText = document.querySelector('.music-text');

        let isPlaying = false;
        let isMinimized = true; // 默认为收缩状态

        // 设置音量
        backgroundMusic.volume = 0.3;

        // 尝试自动播放（需要用户交互后才能真正播放）
        const attemptAutoplay = () => {
            backgroundMusic.play().then(() => {
                isPlaying = true;
                // 如果按钮展开状态，更新文本
                if (!isMinimized) {
                    musicText.textContent = '暂停音乐';
                }
            }).catch(() => {
                // 自动播放失败，保持静音状态
                console.log('自动播放被浏览器阻止，需要用户交互');
            });
        };

        // 页面加载完成后尝试自动播放
        attemptAutoplay();

        // 音乐控制按钮点击事件
        musicControl.addEventListener('click', function(e) {
            e.stopPropagation();

            if (isMinimized) {
                // 展开按钮
                this.classList.remove('minimized');
                isMinimized = false;

                // 如果之前在播放，保持播放状态
                if (isPlaying) {
                    musicText.textContent = '暂停音乐';
                } else {
                    musicText.textContent = '播放音乐';
                }
            } else {
                // 切换播放状态
                if (!isPlaying) {
                    // 首次播放需要取消静音
                    if (backgroundMusic.muted) {
                        backgroundMusic.muted = false;
                    }

                    backgroundMusic.play().then(() => {
                        isPlaying = true;
                        musicText.textContent = '暂停音乐';
                    }).catch(error => {
                        console.log('播放失败:', error);
                        alert('播放音乐失败');
                    });
                } else {
                    // 暂停音乐
                    backgroundMusic.pause();
                    isPlaying = false;
                    musicText.textContent = '播放音乐';
                }
            }
        });

        // 点击页面其他地方收缩按钮
        document.addEventListener('click', function() {
            if (!isMinimized) {
                musicControl.classList.add('minimized');
                isMinimized = true;
            }
        });
    });

    // 萌照上传功能 - 改进版本
    // 修改文件选择监听器部分
    const photoInput = document.getElementById('photoInput');
    const previewContainer = document.getElementById('previewContainer');
    const previewGrid = document.getElementById('previewGrid');
    const captionContainer = document.getElementById('captionContainer');

    // 监听文件选择变化
    photoInput.addEventListener('change', function() {
        // 清空之前的预览和描述输入框
        previewGrid.innerHTML = '';
        captionContainer.innerHTML = '';

        if (this.files && this.files.length > 0) {
            // 显示预览区域
            previewContainer.style.display = 'block';

            // 为每个选中的文件创建预览和描述输入框
            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];

                // 创建预览元素
                const previewItem = document.createElement('div');
                previewItem.style.display = 'flex';
                previewItem.style.flexDirection = 'column';
                previewItem.style.alignItems = 'center';

                // 创建预览图片
                const previewImg = document.createElement('img');
                previewImg.style.width = '100px';
                previewImg.style.height = '100px';
                previewImg.style.objectFit = 'cover';
                previewImg.style.borderRadius = '4px';
                previewImg.style.border = '1px solid #ddd';

                // 使用FileReader读取文件并显示预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                };
                reader.readAsDataURL(file);

                // 创建文件名显示
                const fileName = document.createElement('span');
                fileName.textContent = file.name.length > 15 ? file.name.substring(0, 12) + '...' : file.name;
                fileName.style.fontSize = '0.7em';
                fileName.style.marginTop = '5px';
                fileName.style.textAlign = 'center';
                fileName.style.color = '#666';

                // 组装预览项
                previewItem.appendChild(previewImg);
                previewItem.appendChild(fileName);
                previewGrid.appendChild(previewItem);

                // 创建对应的描述输入框容器
                const captionItem = document.createElement('div');
                captionItem.style.marginBottom = '15px';
                captionItem.style.padding = '10px';
                captionItem.style.backgroundColor = '#f9f9f9';
                captionItem.style.borderRadius = '4px';
                captionItem.style.display = 'flex';
                captionItem.style.alignItems = 'center';

                // 创建图片缩略图
                const thumbImg = document.createElement('img');
                thumbImg.style.width = '40px';
                thumbImg.style.height = '40px';
                thumbImg.style.objectFit = 'cover';
                thumbImg.style.borderRadius = '3px';
                thumbImg.style.marginRight = '10px';
                thumbImg.style.border = '1px solid #ddd';

                const thumbReader = new FileReader();
                thumbReader.onload = function(e) {
                    thumbImg.src = e.target.result;
                };
                thumbReader.readAsDataURL(file);

                // 创建描述输入框容器
                const inputContainer = document.createElement('div');
                inputContainer.style.flex = '1';

                // 创建标题
                const captionTitle = document.createElement('div');
                captionTitle.style.display = 'flex';
                captionTitle.style.alignItems = 'center';
                captionTitle.style.marginBottom = '5px';

                const captionNumber = document.createElement('span');
                captionNumber.textContent = `图片 ${i + 1}:`;
                captionNumber.style.fontWeight = 'bold';
                captionNumber.style.marginRight = '8px';

                const captionFileName = document.createElement('span');
                captionFileName.textContent = file.name.length > 20 ? file.name.substring(0, 17) + '...' : file.name;
                captionFileName.style.fontSize = '0.8em';
                captionFileName.style.color = '#666';

                captionTitle.appendChild(captionNumber);
                captionTitle.appendChild(captionFileName);

                // 创建输入框
                const captionInput = document.createElement('input');
                captionInput.type = 'text';
                captionInput.name = 'captions[]';
                captionInput.placeholder = '给这张萌照加个描述吧...';
                captionInput.style.width = '100%';
                captionInput.style.padding = '8px';
                captionInput.style.border = '1px solid #ddd';
                captionInput.style.borderRadius = '4px';
                captionInput.style.boxSizing = 'border-box';

                // 组装描述输入框
                inputContainer.appendChild(captionTitle);
                inputContainer.appendChild(captionInput);

                captionItem.appendChild(thumbImg);
                captionItem.appendChild(inputContainer);
                captionContainer.appendChild(captionItem);
            }
        } else {
            // 隐藏预览区域
            previewContainer.style.display = 'none';
        }
    });

    // 修改上传处理逻辑
    const photoUploadForm = document.getElementById('photoUploadForm');
    if (photoUploadForm) {
        photoUploadForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const photoInput = document.getElementById('photoInput');
            const uploadButton = document.getElementById('uploadButton');

            if (!photoInput.files || photoInput.files.length === 0) {
                alert('请选择至少一张萌照');
                return;
            }

            // 检查文件数量
            if (photoInput.files.length > 10) {
                alert('一次最多上传10张萌照');
                return;
            }

            // 检查每个文件大小
            for (let i = 0; i < photoInput.files.length; i++) {
                const fileSize = photoInput.files[i].size / 1024 / 1024; // in MB
                if (fileSize > 10) {
                    alert(`第${i+1}张萌照大小不能超过10MB`);
                    return;
                }
            }

            // 显示上传中状态
            const originalButtonText = uploadButton.textContent;
            uploadButton.textContent = '上传中...';
            uploadButton.disabled = true;

            const formData = new FormData();

            // 添加所有选中的文件
            for (let i = 0; i < photoInput.files.length; i++) {
                formData.append('photos[]', photoInput.files[i]);
            }

            // 添加对应的描述
            const captionInputs = document.querySelectorAll('input[name="captions[]"]');
            for (let i = 0; i < captionInputs.length; i++) {
                formData.append('captions[]', captionInputs[i].value || '');
            }

            formData.append('_token', csrfToken);

            fetch('{{ route("photo.upload") }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(response => {
                    // 检查响应内容类型
                    const contentType = response.headers.get('content-type');
                    if (!contentType || !contentType.includes('application/json')) {
                        throw new Error('服务器未返回JSON格式响应');
                    }

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('萌照上传成功！');
                        location.reload();
                    } else {
                        alert((data.message || '请重试'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('上传失败，请重试错误信息：' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    uploadButton.textContent = originalButtonText;
                    uploadButton.disabled = false;
                });
        });
    }

    // 蜡烛功能 - 使用后端计数
    function lightCandle() {
        fetch('{{ route("candle.light") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const countElement = document.getElementById('candleCount');
                    countElement.textContent = `已有 ${data.candleCount} 人`;
                    alert('️ 感谢你为D仔点亮一盏灯，它一定感觉到了温暖');
                    location.reload();
                } else {
                    alert('操作失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
    }

    // 留言功能 - 使用后端
    function submitMessage() {
        const input = document.getElementById('messageInput');
        const nameInput = document.getElementById('nameInput');
        const value = input.value.trim();
        if (!value) return alert('请写下一些回忆吧');

        const name = nameInput.value.trim() || '一位朋友';

        // 发送数据到后端
        fetch('{{ route("message.store") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify({
                content: value,
                name: name
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 重新加载页面以显示新留言
                    location.reload();
                } else {
                    alert('提交失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('提交失败，请重试');
            });
    }

    // 加载更多萌照
    function loadMorePhotos() {
        if (!hasMorePhotos) return;

        const button = document.getElementById('loadMorePhotos');
        button.textContent = '加载中...';
        button.disabled = true;
        button.classList.add('loading');

        // 使用 URLSearchParams 构造查询参数
        const params = new URLSearchParams({
            type: 'photos',
            page: photoPage + 1
        });

        fetch('{{ route("home") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.length > 0) {
                    const grid = document.getElementById('photoGrid');

                    data.data.forEach(photo => {
                        const photoItem = document.createElement('div');
                        photoItem.className = 'photo-item';

                        const img = document.createElement('img');
                        img.src = '/storage/' + photo.path;
                        img.alt = photo.caption || 'D仔';

                        const captionDiv = document.createElement('div');
                        captionDiv.className = 'photo-caption ' + (!photo.caption ? 'empty' : '');
                        captionDiv.textContent = photo.caption || '暂无描述';

                        photoItem.appendChild(img);
                        photoItem.appendChild(captionDiv);
                        grid.appendChild(photoItem);
                    });

                    // 更新页码
                    photoPage++;

                    // 更新是否有更多数据的状态
                    hasMorePhotos = data.hasMore;

                    if (hasMorePhotos) {
                        button.textContent = '加载更多萌照';
                        button.disabled = false;
                        button.classList.remove('loading');
                    } else {
                        button.style.display = 'none';
                    }
                } else {
                    hasMorePhotos = false;
                    button.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                button.textContent = '加载更多萌照';
                button.disabled = false;
                button.classList.remove('loading');
                alert('加载失败，请重试');
            });
    }

    // 加载更多留言
    function loadMoreMessages() {
        if (!hasMoreMessages) return;

        const button = document.getElementById('loadMoreMessages');
        button.textContent = '加载中...';
        button.disabled = true;
        button.classList.add('loading');

        // 使用 URLSearchParams 构造查询参数
        const params = new URLSearchParams({
            type: 'messages',
            page: messagePage + 1
        });

        fetch('{{ route("home") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.length > 0) {
                    const list = document.getElementById('messageList');

                    data.data.forEach(message => {
                        const div = document.createElement('div');
                        div.className = 'message';

                        // 使用createTextNode来防止XSS攻击
                        const strong = document.createElement('strong');
                        strong.textContent = message.name;
                        const content = document.createTextNode('：' + message.content);

                        div.appendChild(strong);
                        div.appendChild(content);
                        list.appendChild(div);
                    });

                    // 更新页码
                    messagePage++;

                    // 更新是否有更多数据的状态
                    hasMoreMessages = data.hasMore;

                    if (hasMoreMessages) {
                        button.textContent = '加载更多留言';
                        button.disabled = false;
                        button.classList.remove('loading');
                    } else {
                        button.style.display = 'none';
                    }
                } else {
                    hasMoreMessages = false;
                    button.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                button.textContent = '加载更多留言';
                button.disabled = false;
                button.classList.remove('loading');
                alert('加载失败，请重试');
            });
    }

    // 加载初始数据
    window.onload = function() {
        // 加载初始萌照
        const photos = @json($photos->items());
        const grid = document.getElementById('photoGrid');
        let modal = document.getElementById("imageModal");
        let modalImg = document.getElementById("modalImage");
        let modalCaption = document.getElementById("modalCaption");
        let span = document.getElementsByClassName("close")[0];

        if (photos.length === 0) {
            const placeholder = document.createElement('div');
            placeholder.textContent = '暂无萌照';
            placeholder.style.color = '#aaa';
            placeholder.style.padding = '40px';
            grid.appendChild(placeholder);
        } else {
            photos.forEach(photo => {
                const photoItem = document.createElement('div');
                photoItem.className = 'photo-item';

                const img = document.createElement('img');
                img.src = '/storage/' + photo.path;
                img.alt = photo.caption || 'D仔';

                const captionDiv = document.createElement('div');
                captionDiv.className = 'photo-caption ' + (!photo.caption ? 'empty' : '');
                captionDiv.textContent = photo.caption || '暂无描述';

                photoItem.appendChild(img);
                photoItem.appendChild(captionDiv);
                grid.appendChild(photoItem);
            });

            // 检查是否还有更多萌照
            hasMorePhotos = {{ $photos->hasMorePages() ? 'true' : 'false' }};
            photoPage = {{ $photos->currentPage() }};

            if (hasMorePhotos) {
                document.getElementById('loadMorePhotos').style.display = 'block';
                document.getElementById('loadMorePhotos').onclick = loadMorePhotos;
            }
        }

        // 为所有图片添加点击事件
        document.addEventListener('click', function(e) {
            // 检查点击的是否是图片或图片容器
            if (e.target.tagName === 'IMG' && e.target.closest('.photo-item')) {
                modal.style.display = "block";
                modalImg.src = e.target.src;
                modalCaption.innerHTML = e.target.alt !== 'D仔' ? e.target.alt : 'D仔萌照';

                // 防止背景滚动
                document.body.style.overflow = 'hidden';
            }
        });

// 点击关闭按钮关闭模态框
        span.onclick = function() {
            modal.style.display = "none";
            document.body.style.overflow = 'auto';
        }

// 点击模态框背景关闭
        modal.onclick = function(event) {
            if (event.target === modal) {
                modal.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        }

// ESC键关闭
        document.addEventListener('keydown', function(event) {
            if (event.key === "Escape" && modal.style.display === "block") {
                modal.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        });

        // 加载初始留言
        const messages = @json($messages->items());
        const list = document.getElementById('messageList');

        if (messages.length === 0) {
            const placeholder = document.createElement('div');
            placeholder.textContent = '暂无留言';
            placeholder.style.color = '#aaa';
            placeholder.style.padding = '20px';
            list.appendChild(placeholder);
        } else {
            messages.forEach(message => {
                const div = document.createElement('div');
                div.className = 'message';
                // 使用文本节点来防止XSS攻击
                const strong = document.createElement('strong');
                strong.textContent = message.name;
                const content = document.createTextNode('：' + message.content);
                div.appendChild(strong);
                div.appendChild(content);
                list.appendChild(div);
            });

            // 检查是否还有更多留言
            hasMoreMessages = {{ $messages->hasMorePages() ? 'true' : 'false' }};
            messagePage = {{ $messages->currentPage() }};

            if (hasMoreMessages) {
                document.getElementById('loadMoreMessages').style.display = 'block';
                document.getElementById('loadMoreMessages').onclick = loadMoreMessages;
            }
        }
    };
</script>
<div id="imageModal" class="modal">
    <span class="close">&times;</span>
    <img class="modal-content" id="modalImage">
    <div id="modalCaption" class="modal-caption"></div>
</div>
</body>
</html>
